package com.mes.controller.printer;

import java.io.BufferedReader;
import java.io.Reader;
import java.sql.Clob;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mes.utils.zebra.ZebraPrintUtils;
import com.yy.base.common.dao.Dao;
import com.yy.base.page.Message;
import com.yy.base.util.StringUtil;

@Controller
@RequestMapping("printer")
public class PrinterController {

	@Autowired
	private Dao dao;
	
	@ResponseBody
	@RequestMapping(value="defaultPrinter", method=RequestMethod.POST)
	public Message defaultPrinter(HttpServletRequest request) {
		Message msg = new Message();
		
		String code = request.getParameter("code");
		String bindId = request.getParameter("bindId");
		String printerId = request.getParameter("printerId");
		String clientIp = StringUtil.getClientIp(request);
		
		String sql = "select t.Emes_Barcode_Type_id id, t.bind_type, name from Emes_Barcode_Type t where t.code = ?";
		Map<String, Object> typeMap = dao.queryUnique(sql, code);
		if (typeMap == null) {
			msg.setErrorMessage("未找到编码[" + code + "]对应的打印功能！");
			return msg;
		}
		Map<String, Object> map = null;
		if (printerId != null && !"".equals(printerId)) {
			sql = "select j.Emes_Barcode_join_id, j.printer_ip, j.printer_name" +
					"  from Emes_Barcode_join j" +
					" where j.Emes_Barcode_join_Id = ?";
			map = dao.queryUnique(sql, printerId);
			
			String userId = (String)request.getSession().getAttribute("userId");
			
			//设置为默认打印机
			setDefaultPrinter(clientIp, (String)map.get("EMES_BARCODE_JOIN_ID"), printerId, 
					(String)typeMap.get("BIND_TYPE"), bindId, userId);
		} else {

			sql = "select j.Emes_Barcode_join_id, j.printer_ip, j.printer_name, j.is_default, is_Public, Emes_Barcode_Label_id " +
					"  from Emes_Barcode_join j" +
					" where (j.pc_ip = ? or is_Public = 'Y')" +
					"   and j.emes_barcode_type_id = ?";
			
			boolean bool = false;
			if ("GYS".equals(typeMap.get("BIND_TYPE"))) {
				sql += "	and j.Emes_Vendor_Id = ?";
				bool = true;
			} else if ("KH".equals(typeMap.get("BIND_TYPE"))) {
				sql += "	and j.Emes_Customer_Id = ?";
				bool = true;
			}
			
			List<Map<String, Object>> list = null;
			if (bool) {
				list = dao.query(sql, clientIp, typeMap.get("ID"), bindId);
			} else {
				list = dao.query(sql, clientIp, typeMap.get("ID"));
			}
			
			if (list == null || list.size() == 0) {
				msg.setErrorMessage("此电脑IP未设置默认打印机！");
				return msg;
			}
			
			//当只有一个标签时，直接取第一个标签
			if (list.size() > 1) {
				//获取默认标签
				for (Map<String, Object> m : list) {
					if ("Y".equals(m.get("IS_DEFAULT"))) {
						map = m;
						break;
					}
				}
				if (map == null) {
					for (Map<String, Object> m : list) {
						if ("Y".equals(m.get("IS_PUBLIC"))) {
							map = m;
							break;
						}
					}
				}
			}
			if (map == null && list.size() == 1) {
				map = list.get(0);
			}
			
			if (map == null) {
				msg.put("list", list);
				msg.setErrorMessage("此电脑IP未设置默认打印机！");
				return msg;
			}
		}
		String labelId = (String)map.get("EMES_BARCODE_LABEL_ID");
		msg.put("printerIP", map.get("PRINTER_IP"));
		msg.put("printerName", map.get("PRINTER_NAME"));
		

		//获取打印信息
		sql = "select l.html, l.data_sql, l.detail_sql, l.zpl_data, l.params, l.Type, l.Table_Postion " +
					" from Emes_Barcode_label l " +
					"where l.Emes_Barcode_label_id = ?";
		Map<String, Object> labelData = dao.queryUnique(sql, labelId);
		
		
		List<Map<String, Object>> printData = getPrintData(request, clobToString(labelData.get("DATA_SQL")), 
				clobToString(labelData.get("DETAIL_SQL")), clobToString(labelData.get("PARAMS")));
		
		String printWay = (String)labelData.get("PRINT_WAY");
		if("ZPL".equals(printWay)) {
			String zplData = clobToString(labelData.get("ZPL_DATA"));
			String printerIP = map.get("PRINTER_IP") + "";
			if(StringUtils.isEmpty(zplData)) {
				msg.setErrorMessage("ZPL指令不能为空！");
				return msg;
			}
			for (Map<String, Object> map2 : printData) {
				ZebraPrintUtils.sendZplOverTcp(printerIP, zplData, (String)map2.get("RFID"), map2);
			}
		} else {
			//获取打印明细列
			sql = "select * from Emes_Barcode_Detail where Emes_Barcode_label_id = ? order by seq";
			List<Map<String, Object>> heads = dao.query(sql, labelId);
			msg.put("columns", heads);
			msg.put("data", printData);
			msg.put("listType", labelData.get("TYPE"));
			msg.put("html", clobToString(labelData.get("HTML")));
			msg.put("tablePostion", labelData.get("TABLE_POSTION"));
		}
		msg.setOkMessage("打印成功！");
		return msg;
	}
	
	/**
	 * 获取打印数据
	 * @param request
	 * @param dataSql
	 * @param detailSql
	 * @param param
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> getPrintData(HttpServletRequest request, String dataSql, String detailSql, String param) {
		String ids = request.getParameter("ids");
		String []dataIds = new String[]{request.getParameter("id")};
		
		if (ids != null && !"".equals(ids)) {
			dataIds = ids.split(",");
		}
		Map<String, Object> sqlParams = new HashMap<String, Object>();
		if (param != null && !"".equals(param)) {
			String[] params = param.split(",");
			for (String p : params) {
				sqlParams.put(p, request.getParameter(p));
			}
		}

		Map<String, Object> params = null;
		if (detailSql != null && !"".equals(detailSql) && !"null".equals(detailSql)) {
			Object obj[] = CheckSQLParamsUtil.parseSql(detailSql, null, true);
			detailSql = (String)obj[0];
			
			params = (Map<String, Object>)obj[1];
		} else {
			detailSql = null;
		}
		
		List<Map<String, Object>> result = new ArrayList<>();
		
		for(String id : dataIds) {
			if (id != null) {
				sqlParams.put("id", id);
			}
			List<Map<String, Object>> list = dao.query(dataSql, sqlParams);
			if (list == null || list.isEmpty()) {
				throw new RuntimeException("未搜索到打印数据！");
			}
			for (Map<String, Object> map : list) {
				try {
					//判定如果列表格式，则循环生成
					if (detailSql != null) {
						if (params != null) {
							for (String key : params.keySet()) {
								params.put(key, map.get(key.toUpperCase()));
							}
							if (params.containsKey("id")) {
								params.put("id", id);
							}
						}
						List<Map<String, Object>> data = dao.query(detailSql, params);
						map.put("_Data_List", data);
					}
					result.add(map);
				} catch (Exception e) {
				}
			}
		}
		return result;
	}
	
	//设置默认打印机
	private void setDefaultPrinter(String ip, String typeIp, String printerId, String bindType, String typeId, String userId) {
		//先取消此类型打印对应IP下的所有默认打印机
		String sql = "update Emes_Barcode_join set is_Default = 'N', updated = sysdate, updatedBy = ? " +
				"where pc_ip = ? and Emes_Barcode_Type_id = ?";
		boolean bool = false;
		if ("GYS".equals(bindType)) {
			sql += " and Emes_Vendor_Id = ?";
			bool = true;
		} else if ("KH".equals(bindType)) {
			sql += " and Emes_Customer_Id = ?";
			bool = true;
		}
		if (bool) {
			this.dao.executeSql(sql, userId, ip, typeIp, typeId);
		} else {
			this.dao.executeSql(sql, userId, ip, typeIp);
		}
		
		sql = "update Emes_Barcode_join set is_Default = 'Y', updated = sysdate, updatedBy = ? " +
				"where pc_ip = ? and Emes_Barcode_Type_id = ? and Emes_Barcode_join_Id = ?";
		this.dao.executeSql(sql, userId, ip, typeIp, printerId);
	}
	
	/**
	 * clob 转字符串
	 */
	private String clobToString(Object clob) {
		if (clob == null || !(clob instanceof Clob)) {
			return clob + "";
		}
		StringBuffer sb = new StringBuffer();
		Reader is = null;
		try {
			is = ((Clob)clob).getCharacterStream();
			BufferedReader br = new BufferedReader(is);
			String str = null;
			while ((str = br.readLine()) != null) { // 如果没有到达流的末尾，则继续读取下一行
				sb.append(str).append("\r\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
